var app = getApp();
import $wuxCountDown from '../../component/wux/countdown/index';
import Dialog from '../../component/vant/dialog/dialog';
import Toast from '../../component/vant/toast/toast';
const util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    isIPX: app.globalData.isIPX,
    domain: app.api.xh.downloadDomain,
    is_to_pay: true,
    openid: wx.getStorageSync('openid'),
    order_status_txt: ['', '未支付', '已支付', '已过期', '已取消']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var page = this;
    if (options.device != undefined) {
      page.setData({
        device: options.device
      });
    }

    if (options.curriculum_id != undefined) {
      // 获取课程详情
      app.sendRequest({
        url: app.api.course.curriculum_info,
        data: {
          curriculum_id: options.curriculum_id
        },
        success: function(res) {
          if (res.data != undefined) {
            page.setData({
              course_info: res.data,
              curriculum_id: options.curriculum_id,
              status: options.status,
              openid: page.data.openid
            });
          }
        }
      });

      // 已有订单时获取订单信息
      if (options.status == 4) {
        // 获取订单号
        let param = { content_id: options.curriculum_id, type: 1 };
        app.sendRequest({
          url: app.api.order.get_out_trade_no,
          data: param,
          success: function(res) {
            app.sendRequest({
              url: app.api.order.info,
              data: {
                out_trade_no: res.data.out_trade_no
              },
              success: function(res) {
                if (res.data != undefined) {
                  let trade_info = res.data;
                  let total_fee = (trade_info.total_fee / 100).toFixed(2);
                  trade_info.total_fee = total_fee;
                  let diff_time_stamp = util.getTimeStampDiff(
                    trade_info.create_time
                  );

                  page.setData({
                    trade_info: trade_info
                  });
                  page.initCountDown(diff_time_stamp);
                }
              }
            });
          }
        });
      } else {
        page.setData({
          is_to_pay: false
        });
      }
    }

    if (options.out_trade_no != undefined) {
      app.setPageTitle('订单详情');
      app.sendRequest({
        url: app.api.order.info,
        data: {
          out_trade_no: options.out_trade_no
        },
        success: function(res) {
          if (res.data != undefined) {
            let trade_info = res.data;
            if (options.status != undefined) {
              trade_info.status = options.status;
            }
            let total_fee = (trade_info.total_fee / 100).toFixed(2);
            trade_info.total_fee = total_fee;
            page.setData({
              trade_info: trade_info
            });

            let is_to_pay = false,
              show_bottom_pay_btn = false;
            if (trade_info.status == 1) {
              page.setData({
                show_bottom_pay_btn: true
              });
              let diff_time_stamp = util.getTimeStampDiff(
                trade_info.create_time
              );
              is_to_pay = true;
              page.initCountDown(diff_time_stamp);
            }
            page.setData({
              show_bottom_pay_btn: show_bottom_pay_btn,
              is_to_pay: is_to_pay
            });
          }
        }
      });
    }
    wx.cloud.init();
  },
  initCountDown(diff_time_stamp) {
    let page = this,
      time_stamp = diff_time_stamp ? diff_time_stamp : 0,
      remain_time = 60000 * 30 - time_stamp * 1000 - 1000;
    page.time = new $wuxCountDown({
      date: +new Date() + remain_time,
      onEnd() {
        page.doOrderCancel();
      },
      render(date) {
        const min = this.leadingZeros(date.min, 2) + ':';
        const sec = this.leadingZeros(date.sec, 2) + '';
        page.setData({
          time: min + sec
        });
      }
    });
  },
  needBuy() {
    let page = this;
    // 下订单
    let param = { content_id: page.data.curriculum_id, type: 1, fecility: 2 };
    app.sendRequest({
      url: app.api.order.order,
      data: param,
      method: 'POST',
      header: {
        token: wx.getStorageSync('access_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.out_trade_no != undefined) {
          // 获取统一下单信息
          app.sendRequest({
            url: app.api.order.unifiedorder,
            data: {
              out_trade_no: res.data.out_trade_no,
              type: 2,
              openid: page.data.openid || wx.getStorageSync('openid')
            },
            method: 'POST',
            header: {
              token: wx.getStorageSync('access_token'),
              'content-type': 'application/x-www-form-urlencoded'
            },
            success: function(res) {
              if (res.data != undefined) {
                page.reqPay(res.data);
              }
            }
          });

          // 获取订单详情
          app.sendRequest({
            url: app.api.order.info,
            data: {
              out_trade_no: res.data.out_trade_no
            },
            success: function(res) {
              if (res.data != undefined) {
                let trade_info = res.data;
                let total_fee = (trade_info.total_fee / 100).toFixed(2);
                trade_info.total_fee = total_fee;
                let diff_time_stamp = util.getTimeStampDiff(
                  trade_info.create_time
                );
                page.setData({
                  is_to_pay: true,
                  trade_info: res.data
                });
                page.initCountDown(diff_time_stamp);
              }
            }
          });
        }
      }
    });
  },
  // 已有订单
  haveOrder() {
    let page = this;

    if (page.data.trade_info.out_trade_no != undefined) {
      // 获取统一下单信息
      app.sendRequest({
        url: app.api.order.unifiedorder,
        data: {
          out_trade_no: page.data.trade_info.out_trade_no,
          type: 2,
          openid: page.data.openid || wx.getStorageSync('openid')
        },
        method: 'POST',
        header: {
          token: wx.getStorageSync('access_token'),
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function(res) {
          if (res.data != undefined) {
            page.reqPay(res.data);
          }
        }
      });
    }
  },
  goPay: function(e) {
    var page = this;
    if (page.data.device == 1) {
      //WEB端订单提示
      Dialog.alert({
        message: '此订单是WEB端订单,请到web端进行支付'
      }).then(() => {
        return false;
      });
    } else {
      if (page.data.is_to_pay) {
        // 已有订单
        page.haveOrder();
      } else {
        // 需要购买
        page.needBuy();
      }
    }
  },
  // 取消订单
  cancelOrder: function(e) {
    var page = this;

    Dialog.confirm({
      title: '提示',
      message: '确定取消订单吗'
    })
      .then(() => {
        page.doOrderCancel();
      })
      .catch(() => {
        // on cancel
      });
  },
  doOrderCancel() {
    let page = this;
    app.sendRequest({
      url: app.api.order.option,
      data: {
        out_trade_no: page.data.trade_info.out_trade_no,
        status: 4
      },
      method: 'POST',
      header: {
        token: wx.getStorageSync('access_token'),
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        page.time.stop();
        Toast({
          duration: 800,
          message: '取消成功！',
          onClose: function name(params) {
            let trade_info = page.data.trade_info;
            trade_info.status = 4;
            page.setData({
              trade_info: trade_info,
              is_to_pay: false
            });
          }
        });
      }
    });
  },
  reqPay(pay_data) {
    let page = this;
    //发起支付
    wx.requestPayment({
      timeStamp: pay_data.timeStamp,
      nonceStr: pay_data.nonce_str,
      package: pay_data.package,
      signType: pay_data.signType,
      paySign: pay_data.paySign,
      success: function(e) {},
      fail: function(e) {},
      complete: function(e) {
        if (
          e.errMsg == 'requestPayment:fail' ||
          e.errMsg == 'requestPayment:fail cancel'
        ) {
          wx.cloud.callFunction({
            name: 'cancel_pay',
            data: {
              order_time: page.data.trade_info.create_time,
              out_trade_no: page.data.trade_info.out_trade_no,
              name: page.data.trade_info.name,
              total_fee: page.data.trade_info.total_fee,
              curriculum_id: page.data.curriculum_id,
              form_id: pay_data.package.replace('prepay_id=', ''),
              deadline_time: util.getTimePlusOneHalfHour(
                page.data.trade_info.create_time
              )
            }
          });
          //支付失败
          Dialog.alert({
            message: '订单尚未支付'
          }).then(() => {
            let trade_info = page.data.trade_info;
            trade_info.status = 1;
            page.setData({
              trade_info: trade_info
            });
          });
          return;
        }
        if (e.errMsg == 'requestPayment:ok') {
          let curriculum_id = wx.getStorageSync('current_curriculum_id'),
            curriculum_name = wx.getStorageSync('current_curriculum_name');

            wx.cloud.callFunction({
              name: 'pay_success',
              data: {
                order_time: page.data.trade_info.create_time,
                out_trade_no: page.data.trade_info.out_trade_no,
                pay_time: util.formatDate(new Date().getTime()),
                total_fee: page.data.trade_info.total_fee,
                name: page.data.trade_info.name,
                curriculum_id: page.data.curriculum_id,
                form_id: pay_data.package.replace('prepay_id=', ''),
                pay_fee: page.data.trade_info.total_fee
              }
            });

          Toast({
            message: '支付成功！',
            duration: 1000,
            onClose: function name(params) {
              // 支付成功
              wx.redirectTo({
                url:
                  '/pages/course_detail/course_detail?curriculum_id=' +
                  curriculum_id +
                  '&curriculum_name=' +
                  curriculum_name
              });
            }
          });

          return;
        }
        wx.redirectTo({
          url: '/pages/my_order/my_order'
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let page = this;
    if (page.data.openid == undefined) {
      page.setData({
        openid: wx.getStorageSync('openid')
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {}
});
